package logic

import (
	"context"
	"shop/pkg"
	"shop/shopRpc/shoprpcclient"
	"strconv"

	"shop/api/internal/svc"
	"shop/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	if !pkg.IsMobile(req.Mobile) {
		return &types.Response{
			Code:    400,
			Message: "手机号码格式错误",
			Data:    nil,
		}, nil
	}

	login, err := l.svcCtx.ShopRpc.UserLogin(l.ctx, &shoprpcclient.UserLoginRequest{
		Tel:      req.Mobile,
		Code:     req.Code,
		Password: req.Password,
	})
	if err != nil {
		return nil, err
	}
	if login.UserId == 0 {
		return &types.Response{
			Code:    500,
			Message: "登录失败",
			Data:    nil,
		}, nil
	}
	token := pkg.TokenHandler(strconv.FormatInt(login.UserId, 10))
	return &types.Response{
		Code:    200,
		Message: "登录成功",
		Data:    token,
	}, nil
}
